package dao;

import static common.Constants.EMPTY_LIST;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import common.Constants;

import domain.Admin;
import domain.User;
import domain.UserRelation;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	private final static Logger logger = Logger.getLogger(UserDaoImpl.class);

	// 类似搜索
	@Override
	public User findUserById(Integer id) {
		// 如果是load必须确保数据库中存在数据，不然会出现错误
		// User user = getHibernateTemplate().load(User.class, id);
		// get的话如果不存在就是返回null
		User user = (User) getHibernateTemplate().get(User.class, id);
		return user;
	}

	@Override
	public User findUserByName(String name) {
		String HQL = "From User u where u.userInfomation.name =?";
		@SuppressWarnings("unchecked")
		List<User> users = getHibernateTemplate().find(HQL, new Object[] { name });
		if (users == null || users.isEmpty()) {
			return null;
		}
		return users.get(0);
	}

	@Override
	public List<User> findUsersByLikeName(final String name,final Integer pageSize, final Integer pageNumber)  {
		final String HQL = "From User u where u.userInfomation.name like :name";
		// List<User> users = getHibernateTemplate().find(HQL,new Object[]{name+"%"});
		// 下面的可以用上面的代替
		@SuppressWarnings("unchecked")
		List<User> users = (List<User>) getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public List<User> doInHibernate(Session session) throws HibernateException, SQLException {
				if (session != null && session.isOpen()) {
					Query query = session.createQuery(HQL);
					query.setParameter("name", name + "%");
					query.setFirstResult(pageSize * (pageNumber - 1));
					query.setMaxResults(pageSize); 
					List<User> users = query.list();
					return users;
				}
				return null;
			}
		});
		if (users == null || users.isEmpty()) {
			return EMPTY_LIST;
		}
		return users;
	}

	// 类似注册
	@Override
	public User addUser(final User user) {
		// recored the operation time
		user.setOperationDate(new Date());
		User savedUser = 
			(User) this.getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public User doInHibernate(Session session) throws HibernateException, SQLException {
				if(session!=null && session.isOpen()) {
					session.save(user);
					return user;
				}
				return null;
			}
		});
			return savedUser;
	}

	@Override
	public Long countAllUsers() {
		@SuppressWarnings("unchecked")
		Long totalCount = (Long) getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Long doInHibernate(Session session) throws HibernateException, SQLException {
				if (session != null && session.isOpen()) {
					String hql = "SELECT COUNT(u.id) FROM User u";
					Query query = session.createQuery(hql);
					List<Long> list = query.list();
					if (list != null) {
						return list.get(0);
					} else {
						return new Long(0);
					}
				}
				return new Long(0);
			}
		});
		return totalCount;
	}

	@Override
	public User updaetUser(User user) {
		// recored the operation time
		user.setOperationDate(new Date());
		getHibernateTemplate().saveOrUpdate(user);
		return user;
	}

	@Override
	public User login(final String registerName, final String password) {
		@SuppressWarnings("unchecked")
		User user = (User) getHibernateTemplate().execute(new HibernateCallback() {
			@SuppressWarnings("null")
			@Override
			public User doInHibernate(Session session) throws HibernateException, SQLException {
				if (session != null && session.isOpen()) {
					String hql = "FROM User u WHERE u.registerName=:registerName AND u.password=:password";
					Query query = session.createQuery(hql);
					query.setString("registerName", registerName);
					query.setString("password", password);
					List<User> users = query.list();
					if (users != null || !users.isEmpty()) {
						User user = users.get(0);
						user.setLoginDate(new Date());
						// recored the operation time
						user.setOperationDate(new Date());
						return user;
					}
					return null;
				}
				return null;
			}
		});
		return user;
	}

	@Override
	public void deleteUserById(final Integer id) {
		getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public UserRelation doInHibernate(Session session) throws HibernateException, SQLException {
				if (session != null && session.isOpen()) {
					String sql =
						new StringBuilder().append("DELETE FROM ").append(Constants.getDefaultSchema())
							.append(".t_user ").append(" WHERE ").append(" t_id=:id ").toString();
					SQLQuery query = session.createSQLQuery(sql);
					query.setInteger("id", id);
					query.executeUpdate();
				}
				return null;
			}
		});
	}
}
